package org.jeecg.hr.controller;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.hr.entity.OfficeDoc;
import org.jeecg.hr.service.OfficeDocService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysUserMapper;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * @Description: 公文信息
 * @Author: MxpIO
 */
@Api(tags = "公文信息")
@RestController
@RequestMapping("/hr/officedoc")
public class OfficeDocController extends JeecgController<OfficeDoc, OfficeDocService> {
	
	@Value("${jeecg.wx.hr.agentId}")
	private Integer agentId;

	@Autowired
	private OfficeDocService officeDocService;
	
	@Autowired
	private ISysDepartService iSysDepartService;
	
	@Autowired
	private ISysBaseAPI iSysBaseAPI;
	
	@Autowired
	private SysUserMapper sysUserMapper;

	/*---------------------------------主表处理-begin-------------------------------------*/

	/**
	 * 分页列表查询
	 * 
	 * @param officeDoc
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "公文信息-分页列表查询")
	@ApiOperation(value = "公文信息-分页列表查询", notes = "公文信息-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(OfficeDoc officeDoc,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		QueryWrapper<OfficeDoc> queryWrapper = QueryGenerator.initQueryWrapper(officeDoc,
				req.getParameterMap());
		queryWrapper.orderByDesc("top_type","out_date");
		Page<OfficeDoc> page = new Page<OfficeDoc>(pageNo, pageSize);
		IPage<OfficeDoc> pageList = officeDocService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 * 公文信息-公文收发单位
	 * @return
	 */
	@AutoLog(value = "公文信息-公文收发单位")
	@ApiOperation(value = "公文信息-公文收发单位", notes = "公文信息-公文收发单位")
	@GetMapping(value = "/queryDocOrg")
	public Result<?> queryDocOrg(){
		QueryWrapper<SysDepart> qw = new QueryWrapper<>();
		qw.eq("org_type", "1").or().eq("org_type", "2");
		List<SysDepart> list = iSysDepartService.list(qw);
		return Result.OK(list);
	}
	
	/**
	 * 分页列表查询
	 * 
	 * @param officeDoc
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "用户公文信息-分页列表查询")
	@ApiOperation(value = "用户公文信息-分页列表查询", notes = "用户公文信息-分页列表查询")
	@GetMapping(value = "/listByUser")
	public Result<?> queryPageListByUser(OfficeDoc officeDoc,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req){
		QueryWrapper<OfficeDoc> queryWrapper = QueryGenerator.initQueryWrapper(officeDoc,
				req.getParameterMap());
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
		String orgCode = sysUser.getOrgCode();
		SysDepart dept = iSysDepartService.getOne(new QueryWrapper<SysDepart>().eq("org_code", orgCode));
		if("2".equals(dept.getOrgType())){
			SysDepart parent = iSysDepartService.getById(dept.getParentId());
			queryWrapper.and(wrapper -> wrapper.eq("dept_code", dept.getOrgCode()).or().like("dept_code", dept.getOrgCode()+",").or().eq("dept_code", parent.getOrgCode()).or().like("dept_code", parent.getOrgCode()+","));
		}else if(!"1".equals(dept.getOrgType())){
			SysDepart parent = getParentDepart(dept, "2");
			SysDepart root = iSysDepartService.getById(parent.getParentId());
			queryWrapper.and(wrapper -> wrapper.eq("dept_code", parent.getOrgCode()).or().like("dept_code", parent.getOrgCode()+",").or().eq("dept_code", root.getOrgCode()).or().like("dept_code", root.getOrgCode()+","));
		}
		queryWrapper.orderByDesc("top_type","out_date");
		Page<OfficeDoc> page = new Page<OfficeDoc>(pageNo, pageSize);
		IPage<OfficeDoc> pageList = officeDocService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	private SysDepart getParentDepart(SysDepart dept, String orgType){
		
		SysDepart parent = iSysDepartService.getById(dept.getParentId());
		if(parent == null){
			return null;
		}
		if(orgType.equals(parent.getOrgType())){
			return parent;
		}else {
			return getParentDepart(parent, orgType);
		}
	}
	
	/**
	 * 添加
	 *
	 * @param officeDoc
	 * @return
	 */
	@AutoLog(value = "公文信息-添加")
	@ApiOperation(value = "公文信息-添加", notes = "公文信息-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody OfficeDoc officeDoc) {
		if(officeDocService.save(officeDoc)){
			try{
				String orgCodeStr = officeDoc.getDeptCode();
				
				if(orgCodeStr != null){
					String[] orgCodes = orgCodeStr.split(",");
					Set<String> users = new HashSet<>();
					for(String orgCode : orgCodes){
						users.addAll(sysUserMapper.selectList(new QueryWrapper<SysUser>().likeLeft("org_code", orgCode)).stream().map(SysUser::getUsername).collect(Collectors.toSet()));
					}
					
					MessageDTO msg = new MessageDTO();
	                msg.setFromUser(officeDoc.getSigner());
	                msg.setToUser(String.join(",", users));
	                msg.setTitle("公文公告："+officeDoc.getTitle());
	                msg.setContent(officeDoc.getSigner() + "签发了公文【"+officeDoc.getCode()+"】《"+officeDoc.getTitle()+"》");
	                msg.setCategory("2");
	                iSysBaseAPI.sendSysAnnouncement(msg);
					
				}
            }catch (Exception e) {
			}
			return Result.OK("添加成功！");
		}else{
			return Result.error("添加失败！");
		}
		
	}

	/**
	 * 编辑
	 *
	 * @param officeDoc
	 * @return
	 */
	@AutoLog(value = "公文信息-编辑")
	@ApiOperation(value = "公文信息-编辑", notes = "公文信息-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody OfficeDoc officeDoc) {
		if(officeDocService.updateById(officeDoc)){
			return Result.OK("编辑成功！");
		}else{
			return Result.error("编辑失败！");
		}
	}
	
	/**
	 * 已读
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公文信息-已读")
	@ApiOperation(value = "公文信息-已读", notes = "公文信息-已读")
	@GetMapping(value = "/read/{id}")
	public Result<?> read(@PathVariable("id") String id) {
		LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
		OfficeDoc doc = officeDocService.getById(id);
		String readed = doc.getReaded();
		boolean update = true;
		if(readed == null){
			doc.setReaded("["+sysUser.getRealname()+"]("+sysUser.getUsername()+")");
		}else{
			if(readed.indexOf("("+sysUser.getUsername()+")") == -1){
				doc.setReaded(doc.getReaded()+",["+sysUser.getRealname()+"]("+sysUser.getUsername()+")");
			}else{
				update = false;
			}
		}
		if(update){
			officeDocService.updateById(doc);
		}
		return Result.OK();
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公文信息-通过id删除")
	@ApiOperation(value = "公文信息-通过id删除", notes = "公文信息-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
		if(officeDocService.removeById(id)){
			return Result.OK("删除成功！");
		}else{
			return Result.error("删除失败！");
		}
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "公文信息-批量删除")
	@ApiOperation(value = "公文信息-批量删除", notes = "公文信息-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		if(officeDocService.removeByIds(Arrays.asList(ids.split(",")))){
			return Result.OK("批量删除成功！");
		}else{
			return Result.error("批量删除失败！");
		}
	}

	/**
	 * 导出
	 * 
	 * @return
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, OfficeDoc officeDoc) {
		return super.exportXls(request, officeDoc, OfficeDoc.class, "公文信息");
	}

	/**
	 * 导入
	 * 
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		return super.importExcel(request, response, OfficeDoc.class);
	}
	/*---------------------------------主表处理-end-------------------------------------*/

}
